package com.question.java.json.serialization;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @Description:
 * @Author: Jun Yang
 */
public class JsonKit {

    private final static Gson gson;

    private JsonKit() {
        throw new AssertionError();
    }

    static {
        gson = new GsonBuilder().create();
    }

    public static String toJson(final Object src) {
        final String serialization = gson.toJson(src);
        return serialization;
    }

    public static <T> String toJson(final List<T> src) {
        final Type typeOfSrc = new TypeToken<T>() {
        }.getType();
        final String serialization = gson.toJson(src, typeOfSrc);
        return serialization;
    }

    public static <T> T fromJson(String json, final Class<T> type) {
        T instance = gson.fromJson(json, type);
        return instance;
    }

    public static <T> T fromJson(String json, final Type type) {
        T instance = gson.fromJson(json, type);
        return instance;
    }

    public static <T> List<T> fromJsonToList(String json, final Type typeOfList) {
        final List<T> list = gson.fromJson(json, typeOfList);
        return list;
    }
}

